var client = {};
var app = getApp();

// 为了实现每次启动倒计时，上次计时如果未到0，依然结束上次重置为网络剩余时间开始计时
var lastCountTimeId = 0;

// 获取订单详情接口
client.getOrderDetail = function (orderNo, that) {
  my.request({
    url: app.globalData.url + "32614eb0-6c99-4b71-9fb8-d69aa7661cb3",
    method: "POST",
    data: {
      loginToken: app.globalData.token,
      orderNo: orderNo
    },
    headers: {
      "Access-Token": app.globalData.token
    },
    // 期望返回的数据格式，默认json，支持json，text，base64
    dataType: "json",
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        var result = "待支付";
        // status	number	订单状态 0 待支付 1 支付成功 2 支付失败 3 超时关闭
        switch (res.data.data.status) {
          case 0:
            result = "待支付";
            break;
          case 1:
            result = "支付成功";
            break;
          case 2:
            result = "支付失败";
            break;
          case 3:
            result = "超时关闭";
            break;
        }
        that.setData({
          orderNo: orderNo,
          houseIdx: res.data.data.houseIdx,
          status: result,
          buyerName: res.data.data.buyerName,
          buyerIdTypeDesc: res.data.data.buyerIdTypeDesc,
          buyerIdNo: res.data.data.buyerIdNo,
          buildName: res.data.data.buildName,
          fullHouseNo: res.data.data.fullHouseNo,
          actuallyPayAmount: res.data.data.actuallyPayAmount,
          accountName: res.data.data.accountName,
          accountNo: res.data.data.accountNo,
          bankName: res.data.data.bankName,
          offlinePay: res.data.data.offlinePay
        });
        // 选房成功页 切换启动下一个计时器
        if (res.data.data.lastExpireMillis > 0) {
          var miao = parseInt(res.data.data.lastExpireMillis / 1000);
          var minute = parseInt(miao / 60);
          var second = miao - minute * 60;
          lastCountTimeId++;
          client.countTime(minute, second, that);
        } else {
          that.setData({
            time: "支付时间已超时"
          });
        }
      } else {
        app.errorHandling("获取订单详情失败：", res);
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      my.showToast({
        content: "网络错误：" + res.data.errorMsg,
        duration: 2000
      });
    },
    complete: function () { }
  });
};

// 分钟倒计时插件
client.countTime = function (minute, second, that) {
  var countTimeId = lastCountTimeId + 1;
  var Interval = setInterval(function () {
    // console.info(
    //   lastCountTimeId + " 进入 " + countTimeId + " second:  " + second
    // );
    // 如果重新启动倒计时，则当前的和之前的所有倒计时全部结束
    if (lastCountTimeId >= countTimeId) {
      console.log("如果重新启动倒计时，则当前的和之前的所有倒计时全部结束");
      clearInterval(Interval);
    }
    if (second > 0) {
      second--;
    } else if (minute > 0) {
      minute--;
      second = 59;
    } else {
      console.log("时间到");
      clearInterval(Interval);
    }
    var lastWarning = false;
    if (minute == 0 && second == 30) {
      lastWarning = true;
    }

    var second1 = second < 10 ? "0" + second : second;
    var minute1 = minute < 10 ? "0" + minute : minute;
    var time = minute1 + " : " + second1;
    that.setData({
      second: second1,
      minute: minute1,
      time: time,
      lastWarning: lastWarning
    });
  }, 1000);
};

// 进行线上支付前  客户端获取 authcode 接口
client.getAuthCode = function (orderNo) {
  my.getAuthCode({
    scopes: "auth_base", // 主动授权：auth_user，静默授权：auth_base。或者其它scope
    success: res => {
      if (res.authCode) {
        console.log("res.authCode： " + res.authCode);
        // 认证成功
        // 调用自己的服务端接口，让服务端进行后端的授权认证，并且利用session，需要解决跨域问题
        intoOnlinePay(res.authCode, orderNo);
      }
    }
  });
};

// 进入线上支付接口
function intoOnlinePay(authCode, orderNo) {
  console.log("orderNo： " + orderNo);
  my.request({
    url: app.globalData.url + "2a68748c-5962-4d86-b9bd-cb80f0b6448c",
    method: "POST",
    data: {
      authCode: authCode,
      orderNo: orderNo,
      orderType: 1
    },
    headers: {
      "Access-Token": app.globalData.token
    },
    // 期望返回的数据格式，默认json，支持json，text，base64
    dataType: "json",
    // 调用成功的回调函数
    success: function (res) {
      console.log("intoOnlinePay: " + JSON.stringify(res));
      if (res.data.succeed == 0) {
        my.tradePay({
          tradeNO: res.data.data.alipay.trade_no,
          success: function (res) {
            console.log("tradePay: " + JSON.stringify(res));
            my.alert({
              content: "线上支付成功"
            });
            my.redirectTo({
              url: "../orderDetail/orderDetail?orderNo=" + orderNo
            });
          },
          fail: function (res) {
            console.log("tradePay fail: " + JSON.stringify(res));
            my.alert({
              content: "线上支付失败"
            });
          }
        });
      } else {
        app.errorHandling("进入线上支付失败：", res);
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      my.showToast({
        content: "网络错误：" + res.data.errorMsg,
        duration: 2000
      });
    },
    complete: function () { }
  });
};

// 进入线下支付接口
client.offlinePay = function (orderNo) {
  console.log("orderNo： " + orderNo);
  my.request({
    url: app.globalData.url + "2a68748c-5962-4d86-b9bd-cb80f0b6448c",
    method: "POST",
    data: {
      orderNo: orderNo,
      orderType: 2
    },
    headers: {
      "Access-Token": app.globalData.token
    },
    // 期望返回的数据格式，默认json，支持json，text，base64
    dataType: "json",
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        my.redirectTo({
          url: "../orderDetailOffline/orderDetailOffline?orderNo=" + orderNo
        });
      } else {
        app.errorHandling("进入线下支付失败：", res);
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      my.showToast({
        content: "网络错误：" + res.data.errorMsg,
        duration: 2000
      });
    },
    complete: function () { }
  });
};

module.exports = {
  client: client
};